package com.fzy.common.random;

import java.util.HashSet;
import java.util.Random;

public class RandomUtil {
    private RandomUtil() {
    }

    private static String str = "ABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";

    /**
     * 生成20位的随机数，有字母和数字组成
     *
     * @return
     */
    public static String createRandomStr() {

        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 20; i++) {
            int num = (int) (Math.random() * 36);
            buffer.append(str.substring(num, num + 1));
        }
        return buffer.toString();
    }

    /**
     * 生成随机无重复数字高效写法
     *
     * @return
     */
    public static Integer[] noRepeatGen() {
        Random random = new Random();
        Integer[] values = new Integer[20];
        HashSet<Integer> hashSet = new HashSet<>();

        // 生成随机数字并存入HashSet
        while (hashSet.size() < values.length) {
            hashSet.add(random.nextInt(100) + 1);
        }

        values = (Integer[]) hashSet.toArray();

        return values;
    }


    public static void main(String[] args) {
        System.out.println(createRandomStr());

        Random random = new Random();
        Object[] values = new Object[20];
        HashSet<Integer> hashSet = new HashSet<Integer>();

        // 生成随机数字并存入HashSet
        while (hashSet.size() < values.length) {
            hashSet.add(random.nextInt(100) + 1);
        }

        values = hashSet.toArray();

        // 遍历数组并打印数据
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + "\t");

            if ((i + 1) % 10 == 0) {
                System.out.println("\n");
            }
        }
    }
}
